from datetime import datetime

import pytz
import shortuuid

from common.log import logger
from common.mysql.MySQLhelper import get_sql_helper

sqlhelper = get_sql_helper()


def get_old_qr_data_by_apply_name(apply_name):
    value = sqlhelper.fetch_all(
        "select user_id from shequn_qr_code where apply_name = %s; ",
        (apply_name))
    if value != ():
        return value[0][0]
    else:
        return None


def get_max_order_in_qr_code():
    value = sqlhelper.fetch_all(
        "select max(create_order) from shequn_qr_code; ",
        ())
    return value


def update_qr_code_local(today, nick_name, user_id, uuid):
    sqlhelper.update(
        "UPDATE shequn_qr_code SET update_time = %s, is_logging = %s, nick_name = %s, user_id = %s WHERE uuid = %s; ",
        (today, 1, nick_name, user_id, uuid))


def update_qr_code_by_user_id(user_id):
    sqlhelper.update(
        "UPDATE shequn_qr_code SET is_logging = 2 WHERE user_id = %s and is_logging = 1; ",
        (user_id))


def insert_she_qun_qr_code(qr_api1, qr_api2, qr_api3, uuid, the_single_one, create_order, container_id, container_type, create_by):
    tz = pytz.timezone('Asia/Shanghai')
    today = datetime.now(tz).strftime('%Y/%m/%d %H:%M:%S')
    logger.info("today qr_code={}".format(today))
    value = str(shortuuid.ShortUUID().random(20))
    sqlhelper.insert_one(
        "INSERT INTO shequn_qr_code (id, create_time, update_time, code_one, code_two, code_three, uuid, is_logging, single_one, create_order, container_id, container_type, create_by) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s); ",
        (value, today, today, qr_api1, qr_api2, qr_api3, uuid, 0, the_single_one, create_order, container_id, container_type, create_by))


def update_qr_code_apply_name(apply_name, container_id):
    sqlhelper.update(
        "UPDATE shequn_qr_code SET apply_name = %s WHERE container_id = %s; ",
        (apply_name, container_id))


def delete_qr_code_by_apply_name(nickName):
    sqlhelper.delete("DELETE from shequn_qr_code where apply_name = %s", (nickName))
